import axios from 'axios';

const API_URL = 'http://localhost:8080/api/auth/'; // 修改为完整URL，避免代理问题

class AuthService {
    login(username, password) {
        return axios
            .post(API_URL + 'login', {
                username,
                password
            })
            .then(response => {
                if (response.data.token) {
                    // 存储用户数据
                    localStorage.setItem('user', JSON.stringify(response.data));
                    // 单独存储token，方便访问API
                    localStorage.setItem('token', response.data.token);
                    
                    // 设置axios默认Authorization头
                    this.setAuthHeader(response.data.token);
                    
                    console.log("登录成功，token已保存:", response.data.token);
                }
                return response.data;
            });
    }

    logout() {
        localStorage.removeItem('user');
        localStorage.removeItem('token');
        // 清除axios默认头
        delete axios.defaults.headers.common['Authorization'];
        console.log("已登出，token已清除");
    }

    register(userData) {
        // userData expected to be an object: { username, password, email, fullName, phoneNumber, dateOfBirth, address }
        return axios.post(API_URL + 'register', userData);
    }

    getCurrentUser() {
        const userStr = localStorage.getItem('user');
        if (userStr) {
            return JSON.parse(userStr);
        }
        return null;
    }

    getToken() {
        // 优先从单独存储的token获取
        const token = localStorage.getItem('token');
        if (token) {
            return token;
        }
        
        // 如果没有单独存储，从用户对象中获取
        const user = this.getCurrentUser();
        return user ? user.token : null;
    }
    
    // 设置全局认证头
    setAuthHeader(token) {
        if (token) {
            axios.defaults.headers.common['Authorization'] = `Bearer ${token}`;
        } else {
            delete axios.defaults.headers.common['Authorization'];
        }
    }
    
    // 获取认证头部对象
    getAuthHeader() {
        const token = this.getToken();
        if (token) {
            return { Authorization: `Bearer ${token}` };
        }
        return {};
    }
    
    // 检查用户是否有特定角色
    hasRole(requiredRole) {
        const token = this.getToken();
        if (!token) return false;
        
        try {
            const tokenParts = token.split('.');
            if (tokenParts.length !== 3) {
                return false;
            }
            
            // 解码JWT的payload部分
            const payload = JSON.parse(atob(tokenParts[1]));
            console.log("当前用户角色:", payload.roles);
            
            // 处理角色既可能是字符串也可能是数组的情况
            if (payload.roles) {
                if (Array.isArray(payload.roles)) {
                    return payload.roles.includes(requiredRole);
                } else if (typeof payload.roles === 'string') {
                    // 如果是单个角色字符串，直接比较
                    return payload.roles === requiredRole;
                }
            }
            return false;
        } catch (error) {
            console.error("解析JWT时出错:", error);
            return false;
        }
    }
    
    // 初始化认证状态
    initAuth() {
        const token = this.getToken();
        if (token) {
            this.setAuthHeader(token);
            return true;
        }
        return false;
    }
}

const authServiceInstance = new AuthService();

// 初始化时设置全局认证头
authServiceInstance.initAuth();

export default authServiceInstance; 